import {addPrefix, isEmpty} from "jsmethod-extra";
import {SystemConstants} from "./SystemConstants";

/**
 * @author lihh
 * @description 资源缓存的类
 */
class ResourceCache {
  private readonly prefix: string;
  private readonly version: string;

  constructor(version, prefix = "") {
    this.prefix = prefix;
    this.version = version;
  }

  async getCache(cacheKey: string) {
    const finalURL = addPrefix(cacheKey, this.prefix);
    const cache = await caches.open(this.version);

    const res = await cache.match(finalURL);
    return isEmpty(res) ? null : res;
  }

  async setCache(cacheKey: string, body: Response): Promise<Response> {
    const finalURL = addPrefix(cacheKey, this.prefix);
    const cache = await caches.open(this.version);

    await cache.put(finalURL, body);
    return body;
  }
}

export const CacheStrategy = {
  xxvResourceInterceptor: new ResourceCache(
    SystemConstants.CACHE_VERSION,
    "/xxvResourceInterceptor/"
  ),
  yunkanCache: new ResourceCache(SystemConstants.YUNKAN_CACHE_VERSION),
};
